/*
 * LinkQueue.c
 *
 *  Created on: 2011-12-2
 *      Author: tracl01
 */

#include <stdlib.h>
#include <stdio.h>

typedef int Elemtype;
typedef struct QNode{
	Elemtype data;
	struct QNode *next;
}QNode,*QueuePtr;

typedef struct {
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

int initQueue(LinkQueue *Q){
	Q->front = (QueuePtr)malloc(sizeof(QNode));
	if (!Q->front) {
		exit(EXIT_FAILURE);
	}
	Q->rear = Q->front;
	Q->front->next = NULL;
	return EXIT_SUCCESS;
}

int enQueue(LinkQueue *Q, Elemtype e){	//插入的结点都插在队尾，所以无需判断队列是否为空
	QueuePtr newnode = (QueuePtr)malloc(sizeof(QNode));
	if (!newnode) {
		exit(EXIT_FAILURE);
	}
	newnode->data = e;
	newnode->next = NULL;
	Q->rear->next = newnode;
	Q->rear = newnode;
	return EXIT_SUCCESS;
}

int deQueue(LinkQueue *Q, Elemtype *e){
	if (Q->front == Q->rear) {
		return EXIT_FAILURE;
	} else {
		QueuePtr p = Q->front->next;
		*e = p->data;
		Q->front->next = p->next;
		if (Q->rear == p) {			//这里判断队尾指针是否为出队结点比判断p->next是否为空方便好用
			Q->rear = Q->front;
		}
		free(p);					//在需要释放结点的函数里，先定义工作指针无疑省事
		return EXIT_SUCCESS;
	}
}
/*
int main(void){
	LinkQueue Q; Elemtype e;
	if (!initQueue(&Q)) {
		printf("init successful!\n");
	}
	int i;
	for (i = 0; i < 10; ++i) {
		enQueue(&Q, i);
	}
	for (i = 0; i < 10; ++i) {
		deQueue(&Q, &e);
		printf("%d ", e);
	}
	return EXIT_SUCCESS;
}
*/
